package tank.client;

import com.google.gson.Gson;
import tank.client.game.MyPanel;
import tank.client.game.Stage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import javax.swing.*;

public class GameClientHandler extends SimpleChannelInboundHandler<String> {

    public static final int PANEL_WIDTH = 1000;
    public static final int PANEL_HEIGHT = 750;
    public static final int GAME_HEIGHT = 850;
    public static final int DIRECTION_UP = 0;
    public static final int DIRECTION_DOWN = 1;
    public static final int DIRECTION_LEFT = 2;
    public static final int DIRECTION_RIGHT = 3;
    private boolean started;
    private MyPanel panel;
    private Gson gson = new Gson();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        if(!started){
            JFrame frame = new JFrame();
            panel = new MyPanel();
            frame.add(panel);
            frame.setSize(PANEL_WIDTH,GAME_HEIGHT);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            frame.addKeyListener(panel);
            started = true;
        }
        if(s.startsWith("remote:")){
            GameClient.remoteAddress = s.substring(s.indexOf(":") + 1);
        }else {
            Stage stage = gson.fromJson(s, Stage.class);
            panel.setCurrentStage(stage);
            panel.repaint();
        }
    }


}
